<?php
namespace app\admin\controller;
use app\admin\model\Admin as AdminModel;
use think\Db;

class Admin extends Common
{

    public function lst()
    {
        $auth = new Auth();
        // $groups = $auth->getGroups(session('id'));
        $admin = new AdminModel();
        $adminres = $admin->getadmin();
        foreach($adminres as $k=>$v){
            $_groupTitle = $auth->getGroups($v['id']);
            if($_groupTitle){
                $groupTitle = $_groupTitle[0]['title'];
                $v['groupTitle']=$groupTitle;
            }
        }

        $this->assign('adminres',$adminres);
        return view('list');
    }

    public function add()
    {
       if(request()->isPost()){
           // $res=db('admin')->insert(input('post.'));
           $admin = new AdminModel();
           $data = input('post.');
           $validate =  \think\Loader::validate('Admin');
           if(!$validate->scene('add')->check($data)){
               $this->error($validate->getError());
           }
           $res = $admin->addadmin($data);

           if($res){
               $this->success('添加管理员成功',url('lst'));
           }else{
                $this->error('添加管理员失败');
           }
           return;
       }
       $authGroupRes=db('auth_group')->select();
       $this->assign('authGroupRes', $authGroupRes);
        return view();
    }


    public function edit($id)
    {
        $admins=db('admin')->field('id,name,password')->find($id);

        if(request()->isPost()){
            $data = input('post.');
            $validate =  \think\Loader::validate('Admin');
            if(!$validate->scene('edit')->check($data)){
                $this->error($validate->getError());
            }

            $adminM =new AdminModel();

            if($adminM->saveadmin($data,$admins) == '2'){
                $this->error('管理员用户名不得为空');
            }

            if($adminM->saveadmin($data,$admins) !== false){
                $this->success('编辑成功',url('lst'));
            }else{
                $this->error('编辑失败');
            }
            return;
        }

        if(!$admins){
            $this->error('该管理员不存在');
        }
        $authGroupAccess= db('auth_group_access')->where(array('uid'=>$id))->find();
        $authGroupRes = db('auth_group')->select();

        $this->assign(array(
            'admin'=>$admins,
            'authGroupRes'=>$authGroupRes,
            'groupid'=>$authGroupAccess['group_id'],
        ));
        return view();
    }


    public function del($id)
    {
        $adminM=new AdminModel();
        $delnum = $adminM->deladmin($id);
        if($delnum=='1'){
            $this->success('删除管理员成功',url('lst'));
        }else{
            $this->error('删除管理员失败');
        }

    }

    public function logout()
    {
        session(null);
        $this->success('退出系统成功',url('login/index'));
    }


}
